package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.service.BrandService;
import com.leyou.pojo.Brand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController @RequestMapping("brand") public class BrandController {
	@Autowired private BrandService brandServiceImpl;

	/**
	 * 分页查询品牌，把查询到的所有数据信息封装到PageResult中
	 * 分页查询最起码要告诉服务器现在查询哪一页，现在的页容量要多少个
	 *
	 * @param page
	 * @param rows
	 * @param sortBy
	 * @param desc
	 * @param key
	 * @return
	 */
	@GetMapping("page") public ResponseEntity<PageResult<Brand>> queryBrandByPage(
			@RequestParam(value = "page", defaultValue = "1") Integer page,
			@RequestParam(value = "rows", defaultValue = "5") Integer rows,
			@RequestParam(value = "sortBy", required = false) String sortBy,
			@RequestParam(value = "desc", defaultValue = "false") Boolean desc,
			@RequestParam(value = "key", required = false) String key) {
		PageResult<Brand> result = brandServiceImpl
				.queryBrandByPage(page, rows, sortBy, desc, key);
		if (result == null && result.getItems().size() == 0
				&& result.getItems() != null) {
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();//204
		}
		return ResponseEntity.ok(result);
	}

	/**
	 * 新增品牌
	 *
	 * @param brand
	 * @param cids
	 * @return
	 */
	@PostMapping public ResponseEntity<Void> saveBrand(Brand brand,
			@RequestParam("cids") List<Long> cids) {
		//新增商品分类信息时 添加的是商品分类ID（一个品牌可以有多个商品分类，所以是cids）
		//所以传入一个Brand对象和一个cids集合
		this.brandServiceImpl.saveBrand(brand, cids);
		return new ResponseEntity<>(HttpStatus.CREATED);
	}

	/**
	 * 修改品牌管理
	 *
	 * @param brand
	 * @param cids
	 * @return
	 */
	@PutMapping public ResponseEntity<Void> updateBrand(Brand brand,
			@RequestParam("cids") List<Long> cids) {
		this.brandServiceImpl.updateBrand(brand, cids);
		return new ResponseEntity<>(HttpStatus.CREATED);
	}

	/**
	 * 根据BID删除对应品牌管理
	 *
	 * @param bid
	 * @return
	 */
	@DeleteMapping("bid/{bid}") public ResponseEntity<Void> deleteBrand(
			@PathVariable("bid") Long bid) {
		this.brandServiceImpl.deleteBrand(bid);
		return ResponseEntity.status(HttpStatus.CREATED).build();
	}

	/**
	 * 根据分类动态查询品牌
	 */
	@GetMapping("cid/{cid}") public ResponseEntity<List<Brand>> queryBrandByCategory(
			@PathVariable("cid") Long cid) {
		List<Brand> list = this.brandServiceImpl.queryBrandByCategory(cid);
			if(list!=null&&list.size()!=0){
				return ResponseEntity.ok(list);
			}
			return ResponseEntity.status(HttpStatus.NO_CONTENT).build();

	}
}
